package com.xiaorun.portal.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xiaorun.portal.dao.CaseMapper;
import com.xiaorun.portal.modal.Bo.Query;
import com.xiaorun.portal.modal.Vo.Case;
import com.xiaorun.portal.service.ICaseService;
import com.xiaorun.portal.utils.QiNiuImgUpload;
import com.xiaorun.portal.utils.TaleUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.FileCopyUtils;

import javax.xml.bind.DatatypeConverter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by BlueT on 2018/3/3.
 */
@Service
@Slf4j
public class CaseServiceImpl implements ICaseService {

    @Autowired
    private CaseMapper caseMapper;

    @Autowired
    private QiNiuImgUpload qiNiuImgUpload;

    @Override
    public List<Case> list(Map<String, Object> params) {
        Query query = new Query(params != null ? params: new HashMap<>());
        List<Case> cases = caseMapper.list(query);
        return cases;
    }

    @Override
    public PageInfo<Case> list(int pageNum, int pageSize, Map<String, Object> params) {
        PageHelper.startPage(pageNum, pageSize);
        Query query = new Query(params != null ? params: new HashMap<>());
        List<Case> caseList = caseMapper.list(query);
        PageInfo<Case> pageInfo = new PageInfo(caseList);
        return pageInfo;
    }

    @Override
    public Integer save(Case cas) throws Exception{
        String img = cas.getImg();
        if(img.startsWith("data:image/")){
            String[] imgArr = img.split(",");
            img = imgArr[1];
            byte[] b =DatatypeConverter.parseBase64Binary(img);
            img = qiNiuImgUpload.uploadImg(b);
            cas.setImg(img);
        }
        int result;
        if(cas.getId() != null){
            result = caseMapper.update(cas);
        }else{
            result = caseMapper.save(cas);
        }
        return result;
    }

    @Override
    public Case get(Integer id) {
        return caseMapper.get(id);
    }

    @Override
    public Integer remove(int id) {
        return caseMapper.remove(id);
    }

    @Override
    public int countTotal(Map<String, Object> params) {
        Query query = new Query(params != null ? params: new HashMap<>());
        return caseMapper.countTotal(query);
    }
}
